<?php
/**
 * Created by PhpStorm.
 * User: thanatos
 * Date: 2017/10/1
 * Time: 下午8:10
 */

namespace common\models;


use yii\base\Model;
use yii\web\UploadedFile;

class UploadForm extends Model
{
    /**
     * @var UploadedFile
     */
    public $imageFile;
    public $type;
    
    /** @var  用户保存图片的路径 */
    public $save_path;
    /** @var  存数据库的路径 */
    public $upload_path;
    
    /** 轮播图 */
    const FLASH_TYPE = 1;
    /** 商品缩略图 */
    const GOODS_TYPE = 2;
    const ARTICLE_TYPE = 2;
    
    const SCENARIO_CREATE = 'create';
    const SCENARIO_UPDATE = 'update';
    
    public function rules()
    {
        return [
        ];
    }
    
    public function scenarios()
    {
        return [
            self::SCENARIO_CREATE => ['imageFile', 'type'],
            self::SCENARIO_UPDATE => ['imageFile', 'type']
        ];
    }
    
    /**
     * @return bool|File
     */
    public function upload()
    {
        
        if ($this->validate() && !empty($this->imageFile)) {
            /** 计算路径 */
            $this->getPathByType();
            $this->imageFile->saveAs($this->save_path);
            // 插入文件信息表
            $model = new File();
            $model->file_path = $this->upload_path;
            $model->file_type = $this->type;
            return $model->save() ? $model : false;
        } else {
            return false;
        }
    }
    
    private function getPathByType()
    {
        switch($this->type) {
            case self::FLASH_TYPE:
                $dir = 'flash';
                break;
        }
        
        $file_path = $this->imageFile->baseName . '.'. $this->imageFile->extension;
        $save_path = \Yii::getAlias('@uploads') . DIRECTORY_SEPARATOR . $dir;
        $upload_path = '/uploads' . DIRECTORY_SEPARATOR . $dir;
        
        if( !file_exists($save_path) ){
            mkdir($save_path, 0777, true);
        }
        $this->save_path = $save_path . DIRECTORY_SEPARATOR . $file_path;
        $this->upload_path = $upload_path . DIRECTORY_SEPARATOR . $file_path;
    }
}